<template>
    <div id="initial" >
        <div style="display: flex;justify-content: space-between;align-items: center;">
            <div style="color: #000000;font-weight: bold;" class="s-20">基础资料</div>
            <div @click="goback"  class="back">
                <img  src="../../../assets/img/person/back.png" alt="">
                <span class="s-15 pointer">返回</span>
            </div>
        </div>
        <div :class="['user-card', level]">
            <div class="flex-start user-avatar">
                <img  v-if="user.avatar" :src="user.avatar">
                <img v-else src="../../../assets/img/person/defaultAvatar.png" alt="">
            </div>
            <div class="authorize">
                <div class="s-22" style="font-weight: bold;color: #303133;display: flex;align-items: center;">
                    <div>{{ usermessage.fullName }}</div>
                    <img v-if="level == 'svip'" src="../../../assets/img/person/svip.png" alt="">
                    <img v-if="level == 'vip'" src="../../../assets/img/person/vip.png" alt="">
                    <img v-if="level != 'svip' && level != 'vip'" src="../../../assets/img/person/nvip.png" alt="">
                </div>
                <div style="white-space: nowrap ;margin-top: 10px;" class="s-16" v-html="levelTips"></div>
                <div style="margin-top: 20px;display: flex;">
                    <el-input v-arouse @input="change" placeholder="请输入授权码" v-model.trim="code" @contextmenu.native="showRightClickMenu"></el-input>
                    <button @click="authorize" :class="['pointer','button',code===''?'dis-button':'act-button']" :disabled="!code">授权</button>
                    <div @click="showGetCode = true" class="getcode pointer s-14" >
                        获取授权码
                    </div>
                </div>
            </div>
            <div class="level-logo">
                <img v-if="level == 'svip'"  src="../../../assets/img/person/sviplogo.png" alt="">
                <img v-if="level == 'vip'"  src="../../../assets/img/person/viplogo.png" alt="">
            </div>
        </div>
        <div class="get-code-container flex-center" v-if="showGetCode">
            <get-code :showGetCode.sync="showGetCode"></get-code>
        </div>
        <div class="form">
            <div>
                <el-form :model="usermessage" ref="usermessage" label-width="" class="chang-s-form">
                    <el-form-item prop="fullName" label="">
                        <div  class="u_message">
                            <div class="s-16"><span style="margin-right: 30px;width:48px;">姓&nbsp;&nbsp;&nbsp;名</span> {{ usermessage.fullName }}</div>
                            <button class="usermessage_btn" @click="dialog='1'">更换</button>
                        </div>
                        
                    </el-form-item>
                    <el-form-item prop="mobile" label="">
                        <div class="u_message" >
                            <div class="s-16"><span style="margin-right: 30px;width: 48px;">手机号</span>{{ usermessage.mobile }}</div>
                            <button class="usermessage_btn" @click="dialog='2'">更换</button>
                        </div>
                    </el-form-item>
                    <el-form-item prop="schoolName" label="">
                        <div class="u_message" style="">
                            <div class="s-16"><span style="margin-right: 30px;width: 48px;">学&nbsp;&nbsp;&nbsp;校</span>{{ usermessage.schoolName }}</div>
                            <button class="usermessage_btn" @click="dialog='3'">更换</button>
                        </div>
                    </el-form-item>
                </el-form>
                <!-- <el-button type="primary" style="margin-left:63px">保存</el-button> -->
            </div>
            <div class="changeSchool flex-center" v-if="dialog!=='0'">
                <change-school :dialog.sync="dialog" v-if="dialog==='3'" @getuserInitial="getuserInitial">
                </change-school>
                <change-phone :mobileNum="user.mobile" :dialog.sync="dialog" v-if="dialog==='2'" @getuserInitial="getuserInitial"></change-phone>
                <change-name :dialog.sync="dialog" v-if="dialog==='1'" @getuserInitial="getuserInitial"></change-name>
            </div>
        </div>
        <div class="exitBtn" @click="loginOut">退出账号</div>
    </div>
</template>

<script>
import school from '@/content/api/school'
import User from '@/content/api/user'
import store from '../../../store/index.js'
import { SqlLib } from '../../../../../../static/lib/sqlite/SqlLib'
import { SqlLibUser } from '../../../../../../static/lib/sqlite/service/SqlLibUser'
import changeSchool from './initial_dialog/changeSchool'
import changePhone from './initial_dialog/changePhoeNum'
import changeName from './initial_dialog/changeName'
import getCode from '@/content/views/home/home_dialog/GetCode'
import { Book } from '../../../../../../static/lib/sqlite/model/Book'
import { Publisher } from '../../../../../../static/lib/sqlite/model/Publisher'
import { SqlLibBook } from "../../../../../../static/lib/sqlite/service/SqlLibBook";
import { updateUserMessage } from '../../../utils/event'
import { mapMutations } from 'vuex';
import { DownloadCenter } from "../../../../../../static/lib/downloader/DownloadCenter";
const cryUtil = require('../../../../../../static/utils/CrypUtil');
export default {
    inject: ['getuser','changeAuthorzation'],
    components: {
        changeSchool,
        changePhone,
        changeName,
        getCode
    },
    data() {
        return {
            code: '',
            src: null,
            level: '',
            remainderDays: 0,
            showGetCode: false,
            usermessage: {
                mobile: '',
                name: '',
                msgCode: '',
                fullName: '',
                schoolId: '',
                schoolName: ''
            },
            user: {
                vipType: '',
            },
            dialog: '0',
            oldCode: '',
        }
    },
    computed: {
        levelTips() {
            switch (this.user.vipType) {
                case '2':
                    this.src = require('../../../assets/img/person/civilianlogo.png')
                    this.level = 'civilian'
                    return `<div class="s-18 c-color"> 立即点亮  <i >VIP</i> 畅享更多资源</div>`
                    break;
                case '1':
                    this.src = require('../../../assets/img/person/viplogo.png')
                    this.level = 'vip'
                    return `<div class="v-volor s-18">您的VIP权益剩余天数为 : <i style="color: #303133;font-weight: bold;">${this.remainderDays} </i>天</div>`
                    break;
                case '0':
                    this.src = require('../../../assets/img/person/sviplogo.png')
                    this.level = 'svip'
                    return `<div class="s-18 v-volor">您的SVIP权益剩余天数为 : <i style="color: #303133;font-weight: bold;">${this.remainderDays} </i>天</div>`
                    break;
            }
        },
        formatCode() {

        }
    },
    mounted() {
        User.getUserInfo().then(res=>{
            if (res.code === '0') {
                console.log(res);
                this.user.vipType = res.returnValue.isVip
                this.remainderDays = res.returnValue.days
            }
        })
        this.$nextTick(() => {
            this.getuserInitial()
        })
    },
    methods: {
        ...mapMutations(['clearDownLoadCenter']),
        loginOut(){
            let closeTips = ''
            let downloadingTable = DownloadCenter.getInstance().getCurrentDownloadingLesson();
            if (downloadingTable.length === 0) {
                closeTips = '确认退出登录吗？'
            } else {
                closeTips = '课程资源正在下载中，是否确认退出？'
            }
            this.$dialog({
                confirm: '确认',
                cancel: '取消',
                message: closeTips,
                close: false,
                type: "warn"
            }).then(() => {
                this.$electron.ipcRenderer.send('close-all-res')
                //先暂停下载中心的所有下载器
                DownloadCenter.getInstance().pauseAlldownloader();
                //移除下载中心单例
                DownloadCenter.removeInstance();
                this.clearDownLoadCenter()
                localStorage.removeItem("isOffline");
                User.loginOut({}).then(response => {
                    clearInterval(window.postMessageInterval)
                    window.netStatus = false
                    localStorage.removeItem("accesstoken");
                    localStorage.removeItem("refreshToken");
                    this.$router.push({ name: 'login' });
                }).catch(error => {
                    clearInterval(window.postMessageInterval)
                    window.netStatus = false
                    localStorage.removeItem("accesstoken");
                    localStorage.removeItem("refreshToken");
                    this.$router.push({ name: 'login' });
                });
                this.$electron.ipcRenderer.send('hideSuspensionWindow')
            })
        },
        goback () {
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            let user = SqlLibUser.queryCurrentUser(sqlLib)
            let obj = {
                bookId: user.bookId
            }
            if (this.authorzation) {
                if (user.lessonId) {
                    obj.lessonId = user.lessonId
                } else {
                    let book = SqlLibBook.queryChapterLessonByBookId(sqlLib, user.bookId)
                    if (book) {
                        obj.lessonId = book[0].lessonVO[0].id
                    }
                }
            }
            this.$router.push({ name: 'home', params: this.authorzation ? obj : {} })
        },
        change(val, oldval) {
            let trimVal = val.replace(/\s/g, '')
            if (trimVal.length === 0) {
                this.oldCode = ''
                return
            }
            if (trimVal.length > 16) {
                val = trimVal.substr(0, 16)
                this.oldCode = this.code = val.replace(/([^\s]{4})/g, '$1  ')
                return
            }
            if (val.length < this.oldCode.length) return
            this.oldCode = this.code = this.code.replace(/\s/g, '').replace(/([^\s]{4})/g, '$1  ')
        },
        authorize() {
            let rex = new RegExp(/^[0-9a-z]{5,15}[0-9a-z]$/)
            if (!rex.test(this.code.replace(/\s/g, ''))) {
                this.$message.error('授权码错误，请检查后填写')
                return
            }
            let _this = this;
            let mask = this.$downloadmask("#initial", {
                title: '正在授权请稍后',
                time: 15000,
                progress: false,
                full: true,
            });
            User.authRedeemCode({
                redeemCode: _this.code.replace(/\s/g, '')
            }).then(async response => {
                if (response.code == "0") {
                    mask.close()
                    let bookId = response.returnValue ? response.returnValue.bookId : ''
                    let updateUser = await User.getUserInfo()
                    this.remainderDays = updateUser.returnValue.days;
                    this.user.vipType = updateUser.returnValue.isVip;

                    let sqlLib = SqlLib.getInstance(window.$DBDIR)
                    let user = SqlLibUser.queryCurrentUser(sqlLib)
                    user.vipType = cryUtil.aesEncrypt(updateUser.returnValue.isVip + "", user.id + "", true);
                    user.remainderDays = cryUtil.aesEncrypt(updateUser.returnValue.days + "", user.id + "", true);
                    sqlLib.updateObjectById(user);
                    console.log(user);
                    SqlLibBook.updateBookAuthorization(sqlLib, bookId);
                    updateUserMessage()
                    if (bookId && bookId !== '') {
                        let newBook = new Book()
                        let newPubliser = new Publisher()
                        newBook.id = bookId
                        let book = sqlLib.selectObjectById(newBook)
                        let bookName = book.name || ''
                        let eduName = ''
                        if (book.publisherId) {
                            newPubliser.id = book.publisherId
                            eduName = sqlLib.selectObjectById(newPubliser).name
                        }
                        this.$dialog({
                            confirm: '确定',
                            message: `${eduName}${bookName}授权成功`,
                            type: 'success'
                        }).then(() => {
                            _this.getuser(true)
                            store.state.becomeVip = true  //通知资源中心变成VIP了
                            _this.changeAuthorzation()
                        })
                    } else {
                        _this.changeAuthorzation()
                        _this.$message.success("授权成功！");
                        store.state.becomeVip = true  //通知资源中心变成VIP了
                        _this.getuser(true)
                    }
                } else {
                    mask.close()
                    _this.$message.warning("授权失败，请联系小美客服！");
                }
            }).catch(error => {
                mask.close()
                console.log(error)
                _this.$message.warning("授权失败，请联系小美客服！");
            })
        },
        getuserInitial() {
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            this.user = SqlLibUser.queryCurrentUser(sqlLib)
            let curVipType = this.user.vipType;
            curVipType = cryUtil.aesDecrypt(curVipType, this.user.id, true);
            curVipType = new Buffer(curVipType, 'base64').toString('utf8');
            this.user.vipType = curVipType;

            this.usermessage.fullName = this.user.name
            this.usermessage.mobile = this.user.mobile.slice(0, 3) + "****" + this.user.mobile.slice(7)
            this.usermessage.schoolName = this.user.schoolName
            let curDays = this.user.remainderDays;
            curDays = cryUtil.aesDecrypt(this.user.remainderDays, this.user.id, true);
            curDays = new Buffer(curDays, 'base64').toString('utf8');
            curDays = parseInt(curDays);
            this.remainderDays = curDays < 0 ? 0 : curDays;
        },
        close() {
            this.dialog = '0'
        },
        showRightClickMenu() {
            console.log("I'm showRightClickMenu...")
            const { ipcRenderer } = require('electron');
            ipcRenderer.send('sigShowRightClickMenu');
        }
    }

}
</script>

<style lang="scss">
#initial {
    width: 100%;
    padding: 20px 30px;
    .back {
        cursor: pointer;
        width: 88px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #0085FF;
        color: #FFFFFF;
        border-radius: 4px;
        border: 1px solid #D7D7D7;
        img{
            width: 8px;
            height: 11px;
            margin-right: 6px;
        }
    }
    .button {
        width: 65px;
        height: 32px;
        border-radius: 4px;
        margin-right: 15px;
        color: #fff;
        border: none;
        font-size: 14px;
        outline: none;
    }

    .get-code-container {
        position: absolute;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.4);
        z-index: 1024;
    }
    .user-card {
        height: 172px;
        margin: 46px 0 75px;
        padding: 27px 24px;
        border-radius: 4px;
        display: flex;
        position: relative;
        align-items: center;
        .user-avatar{
            width: 100px;
            height: 100px;
            border-radius: 50%;
            img{
                width: 100%;
                border-radius: 50%;
                border: 4px solid #FFFFFF;
            }
        }
        .el-input,
        .el-input__inner {
            background-color: #fff;
            width: 360px;
            height: 32px;
            border-radius: 4px;
        }
        .dis-button {
            background: #dbe1ea;
        }
        .authorize{
            margin-left: 26px;
            img{
                margin-left: 15px;
                width: 42px;
                height: 19px;
            }
        }
        .getcode {
            
            font-size: 14px;
        }
        .level-logo{
            position: absolute;
            right: 0px;
            top: 0;
            img{
                width: 189px;
                height: 161px;
            }
        }
    }
    .civilian {
        background: #F1F1F1;
        .act-button {
            background: #F7B500;
        }
        .getcode {
            width: 104px;
            height: 32px;
            border-radius: 4px;
            border: 1px solid #EAA33B;
            color: #EAA33B;
            text-align: center;
            line-height: 32px;
        }
    }
    .vip {
        background: #FFF0F0;
        .act-button {
            background: #F7B500;
        }
        .getcode {
            width: 104px;
            height: 32px;
            border-radius: 4px;
            border: 1px solid #EAA33B;
            color: #EAA33B;
            text-align: center;
            line-height: 32px;
        }
    }
    .svip {
        background: #FFF6E4;
        .act-button {
            background: #F7B500;
        }
        .getcode {
            width: 104px;
            height: 32px;
            border-radius: 4px;
            border: 1px solid #EAA33B;
            color: #EAA33B;
            text-align: center;
            line-height: 32px;
        }
    }
    .form {
        .u_message{
            padding-bottom: 22px;
            color: #303133;
            display: flex;
            justify-content:space-between; 
            border-bottom: 1px dashed #DEE2E6;
        }
        .usermessage_btn{
            width: 88px;
            height: 32px;
            line-height: 32px;
            background: #FFFFFF;
            border-radius: 4px;
            color: #0085FF;
            border: 1px solid #0085FF;
            cursor: pointer;
        }
        // flex: 1;
        .chang-s-form {
            .el-form-item__label {
                text-align: justify;
                text-align-last: justify;
                padding: 0;
            }
        }
        .once-tips {
            width: 113px;
            height: 14px;
            font-size: 14px;
            color: rgba(143, 147, 153, 1);
            line-height: 40px;
        }
    }
    .exitBtn{
        width: 88px;
        height: 32px;
        color: #606266;
        background: #FFFFFF;
        border-radius: 4px;
        border: 1px solid #D5D5D5;
        text-align: center;
        line-height: 32px;
        margin-top: 50px;
        font-size: 14px;
        cursor: pointer;
    }
    .changeSchool {
        position: absolute;
        width: 100vw;
        height: 100vh;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.4);
        .get-code {
            margin-right: 20px;
        }
    }
}
</style>
